package luxing.util;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import luxing.web.model.DataGrid;

/**
 * 
 * 类描述：标签工具类
 * 
 * @author: zzc @date： 日期：2012-12-28 时间：上午09:58:00
 * @version 1.1
 * @author liuht 修改不能输入双引号问题解决
 */
public class ListViewUtils {

	private static final Logger logger = Logger.getLogger(ListViewUtils.class);

	public static JSONObject getJson(DataGrid dg) {
		JSONObject jsonObject = null;
		try {
			if (StringUtils.isNotBlank(dg.getFooter())) {
				jsonObject = JSONObject.parseObject(
						listToStr(dg.getResults(), dg.getField().split(","), dg.getTotal(), dg.getFooter().split(",")));
			} else {
				jsonObject = JSONObject
						.parseObject(listToStr(dg.getResults(), dg.getField().split(","), dg.getTotal(), null));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return jsonObject;
	}

	/**
	 * 循环LIST对象拼接EASYUI格式的JSON数据
	 * 
	 * @param fields
	 * @param total
	 * @param results
	 */
	private static String listToStr(List<?> results, String[] fields, int total, String[] footers) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("{\"total\":" + total + ",\"rows\":[");
		int fieldIndex;
		String fieldName;
		for (int resultIndex = 0; resultIndex < results.size(); ++resultIndex) {
			sb.append("{\"state\":\"closed\",");
			Object fieldValue = null;
			for (fieldIndex = 0; fieldIndex < fields.length; ++fieldIndex) {
				fieldName = fields[fieldIndex].toString();
				if (results.get(resultIndex) instanceof Map) {
					fieldValue = ((Map<?, ?>) results.get(resultIndex)).get(fieldName);
				} else {
					fieldValue = getFieldValue(fieldName, results.get(resultIndex));
				}
				sb.append("\"" + fieldName + "\"" + ":\"" + String.valueOf(fieldValue).replace("\"", "\\\"") + "\"");
				if (fieldIndex != (fields.length - 1)) {
					sb.append(",");
				}
			}
			if (resultIndex != (results.size() - 1)) {
				sb.append("},");
			} else {
				sb.append("}");
			}
		}
		sb.append("]");
		if (footers != null && footers.length > 0) {
			sb.append(",");
			sb.append("\"footer\":[");
			sb.append("{");
			// sb.append("\"name\":\"合计\",");
			for (fieldIndex = 0; fieldIndex < footers.length; fieldIndex++) {
				String footerFiled = footers[fieldIndex].split(":")[0];
				Object value = null;
				if (footers[fieldIndex].split(":").length == 2) {
					value = footers[fieldIndex].split(":")[1];
				} else {
					value = getTotalValue(footerFiled, results);
				}
				if (fieldIndex == 0) {
					sb.append("\"" + footerFiled + "\":\"" + value + "\"");
				} else {
					sb.append(",\"" + footerFiled + "\":\"" + value + "\"");
				}
			}
			sb.append("}");
			sb.append("]");
		}
		sb.append("}");
		return sb.toString();
	}

	/**
	 * 获取字段对应值
	 * 
	 * @param filedName
	 * @param obj
	 * @return
	 */
	public static Object getFieldValue(String filedName, Object obj) {
		Object value = "";
		String tempFieldName = "";
		String tempChildName = null;
		ReflectUtil reflectUtil = new ReflectUtil(obj);
		if (filedName.indexOf("_") == -1) {
			if (filedName.indexOf(".") == -1) {
				tempFieldName = filedName;
			} else {
				tempFieldName = filedName.substring(0, filedName.indexOf("."));// 外键字段引用名
				tempChildName = filedName.substring(filedName.indexOf(".") + 1);// 外键字段名
			}
		} else {
			tempFieldName = filedName.substring(0, filedName.indexOf("_"));// 外键字段引用名
			tempChildName = filedName.substring(filedName.indexOf("_") + 1);// 外键字段名
		}
		value = reflectUtil.getMethodValue(tempFieldName) == null ? "" : reflectUtil.getMethodValue(tempFieldName);
		if (value != "" && value != null && (filedName.indexOf("_") != -1 || filedName.indexOf(".") != -1)) {

			if (value instanceof List) {
				Object tempValue = "";
				for (Object listValue : (List) value) {
					tempValue = tempValue.toString() + getFieldValue(tempChildName, listValue) + ",";
				}
				value = tempValue;
			} else {
				value = getFieldValue(tempChildName, value);
			}

		}
		if (value != "" && value != null) {

			value = converUnicode(value.toString());
		}
		return value;
	}

	private static Object converUnicode(String value) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < value.length(); i++) {
			char c = value.charAt(i);
			switch (c) {
			case '\'':
				sb.append("\\\'");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 计算指定列的合计
	 * 
	 * @param filed
	 *            字段名
	 * @param results
	 *            列表数据
	 * @return
	 */
	private static Object getTotalValue(String fieldName, List results) throws Exception {
		BigDecimal sum = new BigDecimal(0);
		try {
			for (int resultIndex = 0; resultIndex < results.size(); resultIndex++) {
				BigDecimal value = new BigDecimal(0);
				String valueStr = String.valueOf(getFieldValue(fieldName, results.get(resultIndex)));
				if (StringUtils.isNotBlank(valueStr)) {
					value = new BigDecimal(valueStr);
				}
				sum = sum.add(value);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return sum;
	}
}
